import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/border_text.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/utils/local_store.dart';
import 'package:grint/utils/whisper.dart';
import 'package:grint/widget/report_dialog.dart';
import 'package:http/http.dart' as http;
import 'dart:math';
import 'package:flutter_markdown/flutter_markdown.dart';

class GuidePage extends StatefulWidget {
  const GuidePage({super.key});

  @override
  State<GuidePage> createState() => _GuidePageState();
}

class _GuidePageState extends State<GuidePage> {
  final TextEditingController _foodController = TextEditingController();
  final TextEditingController _suggestionController = TextEditingController();
  final ScrollController _suggestionScrollController = ScrollController();
  final ScrollController _pageScrollController = ScrollController();
  bool _loading = false;
  List<Map<String, String>> _history = [];
  String? _conversationId;
  String? _sessionId;

  @override
  void initState() {
    super.initState();
    _loadHistory();
    _initSessionId();
  }

  void _initSessionId() {
    final now = DateTime.now();
    final timeStr =
        " ${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}_${now.hour.toString().padLeft(2, '0')}${now.minute.toString().padLeft(2, '0')}${now.second.toString().padLeft(2, '0')}";
    final rand = List.generate(16, (_) => Random().nextInt(10)).join();
    _sessionId = "${timeStr}_$rand";
  }

  Future<void> _search() async {
    final food = _foodController.text.trim();
    if (food.isEmpty) return;
    setState(() => _loading = true);
    final body = {
      "bundle_id": "com.grint.ios",
      "content":
          "Give me a dental health diet guide for $food. Focus on how this food affects teeth and gums, and provide tips for maintaining oral health. Please keep your response under 1000 characters.",
      "content_type": "text",
      "session_id": _sessionId,
      if (_conversationId != null) "conversation_id": _conversationId,
    };
    try {
      final resp = await http.post(
        Uri.parse("https://api.wiseaii.com/wiseai/v1/chat"),
        headers: {"Content-Type": "application/json"},
        body: jsonEncode(body),
      );
      setState(() => _loading = false);
      if (resp.statusCode == 200) {
        final data = jsonDecode(resp.body);
        final answer = data['data']?['answer'] ?? '';
        final conversationId = data['data']?['conversation_id'];
        if (answer.isNotEmpty) {
          _suggestionController.text = answer;
          _conversationId = conversationId;
          await _saveHistory(food, answer);
        } else {
          _suggestionController.text = '';
        }
      } else {
        _suggestionController.text = 'AI API request failed';
      }
    } catch (e) {
      setState(() => _loading = false);
      _suggestionController.text = 'Network error';
    }
    setState(() {});
  }

  Future<void> _saveHistory(String food, String suggestion) async {
    _history.insert(0, {"food": food, "suggestion": suggestion});
    if (_history.length > 20) _history = _history.sublist(0, 20);
    await LocalStore().setObjectValue("food_suggestion_history", {
      "list": _history,
    });
    setState(() {});
  }

  Future<void> _loadHistory() async {
    await LocalStore().init();
    final obj = LocalStore().getObjectValue("food_suggestion_history");
    if (obj != null && obj["list"] is List) {
      _history = List<Map<String, String>>.from(
        (obj["list"] as List).map((e) => Map<String, String>.from(e)),
      );
      setState(() {});
    } else {
      _initSampleData();
    }
  }

  void _jubaoLishiJilu(int index) {
    final item = _history[index];
    final neirong = 'Food: ${item['food']} - Suggestion: ${item['suggestion']}';

    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoNeirongId:
          'history_${index}_${DateTime.now().millisecondsSinceEpoch}',
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _chuliLishiJubao(index, jubaoLeixing, fujiaxinxi, neirong);
      },
    );
  }

  Future<void> _chuliLishiJubao(
    int index,
    JubaoLeixing jubaoLeixing,
    String? fujiaxinxi,
    String neirong,
  ) async {
    _history.removeAt(index);
    await LocalStore().setObjectValue("food_suggestion_history", {
      "list": _history,
    });
    setState(() {});
  }

  void _reset() {
    _foodController.clear();
    _suggestionController.clear();
    setState(() {});
  }

  void _initSampleData() {
    _history = [
      {
        "food": "Coffee",
        "suggestion":
            "**Coffee Dental Health Guide:**\n\n• **Use a straw** to minimize direct contact with teeth\n• **Rinse with water** immediately after drinking\n• **Wait 30 minutes** before brushing to protect enamel\n• **Add milk** to neutralize acidity\n• **Limit to 2-3 cups** daily to prevent staining\n• **Brush gently** to avoid enamel damage",
      },
      {
        "food": "Lemon",
        "suggestion":
            "**Lemon Dental Health Guide:**\n\n• **Consume in moderation** to prevent enamel erosion\n• **Rinse mouth thoroughly** with water after eating\n• **Avoid brushing immediately** - wait 30 minutes\n• **Pair with meals** to reduce acid concentration\n• **Use straw** when drinking lemon water\n• **Consider enamel-strengthening toothpaste**",
      },
      {
        "food": "Chocolate",
        "suggestion":
            "**Chocolate Dental Health Guide:**\n\n• **Choose dark chocolate** (70%+ cocoa) with less sugar\n• **Rinse mouth** thoroughly after consumption\n• **Brush teeth** 30 minutes after eating\n• **Limit portion size** to prevent sugar buildup\n• **Avoid sticky varieties** that cling to teeth\n• **Use fluoride toothpaste** for extra protection",
      },
    ];
    _saveHistoryToLocal();
    setState(() {});
  }

  Future<void> _saveHistoryToLocal() async {
    await LocalStore().setObjectValue("food_suggestion_history", {
      "list": _history,
    });
  }

  @override
  void dispose() {
    _foodController.dispose();
    _suggestionController.dispose();
    _suggestionScrollController.dispose();
    _pageScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: SingleChildScrollView(
              controller: _pageScrollController,
              physics: const ClampingScrollPhysics(),
              child: Column(
                children: [
                  Row(
                    children: [
                      BlackButton(
                        icon: IconFontIcons.iconArrowLeft,
                        onTap: () {
                          context.pop();
                        },
                      ),
                      SizedBox(width: 16.w),
                      Expanded(
                        child: Center(
                          child: MyText(
                            text: 'Diet Guide',
                            type: TextType.rubik,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                      SizedBox(width: 36.w),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColors.black,
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    padding: EdgeInsets.only(bottom: 3.w),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 16.h,
                      ),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment(0.50, 1.50),
                          end: Alignment(0.50, -0.00),
                          colors: [
                            const Color(0xFFD0F8D5),
                            const Color(0xFFC9F6FA),
                          ],
                        ),
                        borderRadius: BorderRadius.circular(20.r),
                        border: Border.all(color: AppColors.white, width: 2.w),
                      ),
                      child: Column(
                        children: [
                          BianKuangText(
                            text: 'Food inquiry',
                            color: AppColors.white,
                            borderColor: AppColors.black,
                            textSize: 26.sp,
                            borderWidth: 3.w,
                          ),
                          SizedBox(height: 16.h),
                          Align(
                            alignment: Alignment.centerLeft,
                            child: MyText(
                              text: 'Food',
                              type: TextType.miSans,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w900,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Container(
                            decoration: BoxDecoration(
                              color: AppColors.white,
                              borderRadius: BorderRadius.circular(16.r),
                              border: Border.all(
                                color: AppColors.black,
                                width: 2.w,
                              ),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            child: TextField(
                              controller: _foodController,
                              onTap: () {},
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w900,
                                color: AppColors.black,
                              ),
                              decoration: InputDecoration(
                                hintText: 'Enter your food',
                                hintStyle: TextStyle(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.w900,
                                  color: AppColors.textGrey,
                                ),
                                border: InputBorder.none,
                              ),
                            ),
                          ),
                          SizedBox(height: 16.h),
                          Align(
                            alignment: Alignment.centerLeft,
                            child: MyText(
                              text: 'Suggestion',
                              type: TextType.miSans,
                              fontSize: 18.sp,
                              fontWeight: FontWeight.w900,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Container(
                            width: double.infinity,
                            constraints: BoxConstraints(
                              minHeight: 80.h,
                              maxHeight: 300.h,
                            ),
                            decoration: BoxDecoration(
                              color: AppColors.white,
                              borderRadius: BorderRadius.circular(16.r),
                              border: Border.all(
                                color: AppColors.black,
                                width: 2.w,
                              ),
                            ),
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 6.h,
                            ),
                            child:
                                _suggestionController.text.isEmpty
                                    ? GestureDetector(
                                      onTap: () {
                                        Whisper.breath(
                                          'Click the Search button to get suggestions',
                                        );
                                      },
                                      child: Padding(
                                        padding: EdgeInsets.only(top: 8.h),
                                        child: Text(
                                          'Press the search button below to get food suggestions',
                                          style: TextStyle(
                                            fontSize: 16.sp,
                                            fontWeight: FontWeight.w900,
                                            color: AppColors.textGrey,
                                          ),
                                        ),
                                      ),
                                    )
                                    : Scrollbar(
                                      thumbVisibility: true,
                                      controller: _suggestionScrollController,
                                      child: SingleChildScrollView(
                                        controller: _suggestionScrollController,
                                        child: MarkdownBody(
                                          data: _suggestionController.text,
                                          styleSheet: MarkdownStyleSheet(
                                            p: TextStyle(
                                              fontSize: 16.sp,
                                              fontWeight: FontWeight.w900,
                                              color: AppColors.black,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),
                          ),
                          SizedBox(height: 16.h),
                          Row(
                            children: [
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: AppColors.black,
                                    borderRadius: BorderRadius.circular(14.r),
                                  ),
                                  padding: EdgeInsets.only(bottom: 3.w),
                                  child: Container(
                                    height: 48.h,
                                    decoration: BoxDecoration(
                                      color: AppColors.white,
                                      borderRadius: BorderRadius.circular(14.r),
                                      border: Border.all(
                                        color: AppColors.black,
                                        width: 2.w,
                                      ),
                                    ),
                                    child: TextButton(
                                      onPressed: _reset,
                                      child: MyText(
                                        text: 'Reset',
                                        type: TextType.rubik,
                                        fontSize: 16.sp,
                                        color: AppColors.black,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              SizedBox(width: 16.w),
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: AppColors.black,
                                    borderRadius: BorderRadius.circular(14.r),
                                  ),
                                  padding: EdgeInsets.only(bottom: 3.w),
                                  child: Container(
                                    height: 48.h,
                                    decoration: BoxDecoration(
                                      color: AppColors.lightBlue,
                                      borderRadius: BorderRadius.circular(14.r),
                                      border: Border.all(
                                        color: AppColors.black,
                                        width: 2.w,
                                      ),
                                    ),
                                    child: TextButton(
                                      onPressed: _loading ? null : _search,
                                      child:
                                          _loading
                                              ? SizedBox(
                                                width: 20,
                                                height: 20,
                                                child:
                                                    CircularProgressIndicator(
                                                      strokeWidth: 2,
                                                    ),
                                              )
                                              : MyText(
                                                text: 'Search',
                                                type: TextType.rubik,
                                                fontSize: 16.sp,
                                                color: AppColors.black,
                                                fontWeight: FontWeight.bold,
                                              ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 6.h),
                  MyText(
                    text: '*The suggestion is for reference only',
                    type: TextType.miSans,
                    fontSize: 14.sp,
                    color: AppColors.black,
                  ),
                  SizedBox(height: 16.h),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Container(
                      width: 241.w,
                      height: 32.h,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage('assets/images/record.png'),
                          fit: BoxFit.contain,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 16.h),
                  // 历史建议列表
                  Column(
                    children: List.generate(_history.length, (index) {
                      final item = _history[index];
                      return Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(
                          bottom: index < _history.length - 1 ? 12.h : 0,
                        ),
                        padding: EdgeInsets.all(16.w),
                        decoration: BoxDecoration(
                          color: AppColors.white,
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(
                            color: AppColors.black,
                            width: 2.w,
                          ),
                        ),
                        child: Stack(
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    MyText(
                                      text: 'Food: ',
                                      type: TextType.rubik,
                                      fontSize: 14.sp,
                                      color: AppColors.black,
                                      fontWeight: FontWeight.bold,
                                    ),
                                    MyText(
                                      text: item['food'] ?? '',
                                      type: TextType.miSans,
                                      fontSize: 14.sp,
                                      color: AppColors.textGrey,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ],
                                ),
                                SizedBox(height: 8.h),
                                MyText(
                                  text: 'Suggestion:',
                                  type: TextType.rubik,
                                  fontSize: 14.sp,
                                  color: AppColors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                                SizedBox(height: 4.h),
                                MarkdownBody(
                                  data: item['suggestion'] ?? '',
                                  styleSheet: MarkdownStyleSheet(
                                    p: TextStyle(
                                      fontSize: 13.sp,
                                      color: AppColors.black,
                                      fontWeight: FontWeight.normal,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Positioned(
                              top: 0,
                              right: 0,
                              child: GestureDetector(
                                onTap: () => _jubaoLishiJilu(index),
                                child: Icon(
                                  IconFontIcons.iconReport,
                                  color: AppColors.textGrey,
                                  size: 20.sp,
                                ),
                              ),
                            ),
                          ],
                        ),
                      );
                    }),
                  ),
                  SizedBox(height: 60.h),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
